package cn.devzyh.oms.wsms.controller;

import cn.devzyh.oms.common.core.util.R;
import cn.devzyh.oms.common.excel.annotation.ResponseExcel;
import cn.devzyh.oms.common.log.annotation.SysLog;
import cn.devzyh.oms.wsms.api.entity.SkuItem;
import cn.devzyh.oms.wsms.service.SkuItemService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 商品分类
 *
 * @author devzyh
 * @date 2023-09-16
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/sku/item")
public class SkuItemController {

	private final SkuItemService skuItemService;

	/**
	 * 返回树形菜单
	 *
	 * @param parentId 父节点ID
	 * @param itemName 分类名称
	 * @return 树形菜单
	 */
	@GetMapping(value = "/tree")
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_view')")
	public R getTree(@RequestParam(required = false) Long parentId, @RequestParam(required = false) String itemName) {
		return R.ok(skuItemService.treeMenu(parentId, itemName));
	}

	/**
	 * 通过ID查询
	 *
	 * @param id id
	 * @return R
	 */
	@GetMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_view')")
	public R getById(@PathVariable("id") Long id) {
		return R.ok(skuItemService.getById(id));
	}

	/**
	 * 新增数据
	 *
	 * @param skuItem 商品分类
	 * @return R
	 */
	@SysLog("新增商品分类")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_add')")
	public R save(@RequestBody SkuItem skuItem) {
		return R.ok(skuItemService.save(skuItem));
	}

	/**
	 * 修改数据
	 *
	 * @param skuItem 商品分类
	 * @return R
	 */
	@SysLog("修改商品分类")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_edit')")
	public R updateById(@RequestBody SkuItem skuItem) {
		return R.ok(skuItemService.updateById(skuItem));
	}

	/**
	 * 通过ID删除
	 *
	 * @param ids id列表
	 * @return R
	 */
	@SysLog("通过ID删除商品分类")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_del')")
	public R removeById(@RequestBody Long[] ids) {
		return R.ok(skuItemService.removeBatchByIds(CollUtil.toList(ids)));
	}

	/**
	 * 导出Excel表格
	 *
	 * @param skuItem 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('wsms_sku_item_export')")
	public List<SkuItem> export(@ModelAttribute SkuItem skuItem) {
		LambdaQueryWrapper<SkuItem> wrapper = Wrappers.lambdaQuery();
		wrapper.likeLeft(StrUtil.isNotBlank(skuItem.getName()), SkuItem::getName, skuItem.getName());
		wrapper.eq(Objects.nonNull(skuItem.getParentId()), SkuItem::getParentId, skuItem.getParentId());
		return skuItemService.list(wrapper);
	}

}